/*
 * Copyright (C) hushenglan
 */

#include "mynet.h"

namespace mynet
{

/*
 * 构造函数，主动连接
 */
CTcpSock::CTcpSock(struct sockaddr_in remoteAddr)
{
    _peerAddr = remoteAddr;
    _sock = socket(AF_INET, SOCK_STREAM, 0);
    _status = MTNET_CONNECTING;
    connect();
    _status = MTNET_CONNECTED;
}

/*
 * 构造函数，被动连接
 */
CTcpSock::CTcpSock(int sock)
{
    _sock = sock;
    _getPeerAddr();
    _status = MTNET_CONNECTED;
}

/*
 * 析构函数
 */
CTcpSock::~CTcpSock()
{
}

/*
 * 主动连接到远程
 *
 * @return 是否成功
 */
bool CTcpSock::connect()
{
    int ret = connect(_sock, (const struct sockaddr*)&_peerAddr, sizeof(_peerAddr));
    if(ret != 0)
    {
        /* error */
        return false;
    }

    return true;
}

/*
 * 根据已经连接的socket获取远程addr
 *
 * @return 是否成功
 */
bool CTcpSock::_getPeerAddr()
{
    int ret = getpeername(_sock, (const struct sockaddr*)&_peerAddr, sizeof(_peerAddr));
    if(ret != 0)
    {
        /* error */
        return false;
    }

    return true;
}

/*
 * 获取socket状态
 *
 * @return 状态
 */
int CTcpSock::getSockStat()
{
    return _status;
}

}
